// $Id: $

var apmap = {

  init: function() {
    $('#awplus_content table:eq(0) a').each(function() {      
      var id = this.href.match(/([0-9]+)$/)[1];
      this.id = id;
      this.href = "javascript:void(0);";

      $(this).click(apmap.attachClick);
    });
  },

  initPlayer: function(e) {
    var pid = this.href.match(/([0-9]+)$/)[1];
    this.id = pid;
    $(this).addClass('applayer');
    this.href = "javascript:void(0);";

    $(this).click(apmap.attachPlayerClick);   
  },

  getSystemData: function(e) {
    var id = this.id;
    var pai = this;

    $('#apsys_'+ id).toFront().html('Loading...');

    $.get('Detail.php/?nr='+id,
      function(data) {
        var syshtml = data.replace(/\n/g, '');
        var systitle = $('table:eq(2) tr:eq(0) td', syshtml).html().replace('Planets at ', '') + ' ['+id+']';
        var aphtml = $('table:eq(2)', syshtml).find('tr:eq(0)').remove().end().html();
        aphtml = '<table cellspacing="1" cellpadding="1" border="0" width="100%" style="padding: 10px;">'+aphtml+'</table>';

        $('#apsys_'+ id)
          .siblings('.ui-dialog-titlebar').children('.ui-dialog-title').html(systitle).end()
        $('#apsys_'+ id)
          .html(aphtml)
          .find('table tr:gt(1) td a')
            .each(apmap.initPlayer)
            .end();
      });
  },
  
  attachClick: function(e) {
    var id = this.id;
    if ($('#apsys_'+ id).dialog('open').size()) { return; }

    this.getSystemData = apmap.getSystemData;
    var pai = this;

    $('body').append('<div id="apsys_'+id+'" class="apsys"></div>');
    
    var pos = $('#'+ id).offset();

    $('#apsys_'+ id).dialog({
        resizable: false,
        position: [pos.left-150, pos.top-175],
        width: 300,
        height: 350,
        buttons: {
          'Reload': function() {
            $(this).text('');
            pai.getSystemData();
          },
          'BBCode': function() {
            var id = $(this).attr('id');
            var bid = id + '_bb';
            var obid = $('#'+bid);
            if (obid.length == 0) {
              var x = $(this).clone();
              x.attr('id', bid);
              $(this).after(x).hide();
              
              $('#'+bid).html('<textarea id="'+bid+'_code" style="margin: 10px; width: 92%; height: 78%;"></textarea>');
              
              var sys = $(this).siblings('.ui-dialog-titlebar').children('.ui-dialog-title').text().match(/(.*?) \((-?\d+\/-?\d+)\) \[(\d+)\]$/);
              
              $('#'+bid+'_code').text('Export of System [b]'+sys[3]+' - '+sys[1]+' ('+sys[2]+')[/b]\r\n[size=13]\r\n[i]pid pop sb   owner[/i][/size][size=14]\r\n');
              
              $('table tr:gt(0)', this).each(function(i) {
                var color;
                switch ($(this).attr('bgcolor')) {
                  case '#602020': color = 'red'; break;
                  case '#305050': color = 'green'; break;
                  case '#404040': color = 'darkgrey'; break;
                }
                var pid = $('td:eq(0)', this).text();
                pid = pid.length == 2 ? pid : '0'+pid;
                var pop = $('td:eq(1)', this).text();
                pop = pop.length == 2 ? pop : '0'+pop;
                var sb = $('td:eq(2)', this).text();
                sb = sb.length == 2 ? sb : '0'+sb;
                var user = $('td:eq(3)', this).text();
                var line = '[color='+color+']'+pid+'  '+pop+'  '+sb+'   '+user+'[/color]\r\n';
                
                $('#'+bid+'_code').append(line);
              });
              $('#'+bid+'_code').append('[/size]\r\nGenerated by [url=http://code.google.com/p/awplus/]awPlus[/url] at '+ new Date().toString());
              $('#'+bid+'_code').focus().get(0).select();
              
            }
            else {
              obid.remove();
              $(this).show();
            }
          },
          'Close': function() { $(this).dialog('close'); }
        }
      });

    this.getSystemData();
  },

  getPlayerData: function(e) {
    var id = this.id;
    var pai = this;

    $('#appla_'+ id).toFront().html('Loading...');

    $.get('/0/Player/Profile.php/?id='+id,
      function(data) {
        var plahtml = data.replace(/\n/g, '');
        var aphtml = '<table width="100%" style="padding: 10px;">';
        aphtml += $('table:eq(2)', plahtml).html();
        aphtml += '</table>';

        var aptitle = $('table tr td center', aphtml).html().replace('Premium Member', '');

        $('#appla_'+ id)
          .siblings('.ui-dialog-titlebar').children('.ui-dialog-title').html(aptitle).end()
        $('#appla_'+ id)
          .html(aphtml)
          .find('table:eq(1) tr:eq(0) td center')
            .append('&nbsp;['+id+']')
          .end()

        if ($('#appla_'+id+' table:eq(0) tr:eq(0) > td').size() == 2) {
          $('#appla_'+id).parents('.ui-dialog').width(460).height(450).end().width(460);
        }
      });   
  },

  attachPlayerClick: function(e) {
    var id = this.id;
    if ($('#appla_'+ id).dialog('open').size()) { return; }

    this.getPlayerData = apmap.getPlayerData;
    var pai = this;

    $('body').append('<div id="appla_'+id+'" class="appla"></div>');

    var pos = $('#'+id).offset();
    
    $('#appla_'+ id).dialog({
        resizable: false,
        position: [pos.left-135, pos.top-205],
        width: 270,
        height: 410,
        dialogClass: 'appladet',
        buttons: {
          'Reload': function() {
            $(this).empty();
            pai.getPlayerData();
          },
          'Close': function() { $(this).dialog('close'); }
        }
      });

    this.getPlayerData();   
  }
};

var jq_zindex = 100;
jQuery.fn.toFront = function() {
  return this.each(function() {
    $(this).css('z-index', ++jq_zindex);
  });
}

$(document).ready(function () {

  // Adding a css for dialog style.
  $('head').append('<link rel="stylesheet" href="http://mutantepower.com.br/awplus-ui/jquery-ui-themeroller2.css" type="text/css" media="screen">');
  apmap.init();

  // Search system form.
  var html = '<div id="ap_findsid" align="center" style="margin: 5px;">'
  html += 'System ID: ';
  html += '<input id="ap_sid" type="text" size="3" class="text" /> ';
  html += '<input id="ap_sid_find" type="button" value="Find" class="smbutton" />';
  html += '</div>';

  $('table:eq(2)').before(html);

  $('#ap_sid').keyup(function(e) {
    if (e.keyCode == 13) {
      $('#ap_sid_find').trigger('click');
    }
  })[0].focus();

  $('#ap_sid_find').click(function() {
    var sid = $('#ap_sid').val();
    var sys = $('#'+ sid);

    if (!sys.size()) {
      alert('System #'+sid+' not found!');
      return;
    }

    sys.effect('shake', {}, 80).effect('pulsate')
  });

});
